package com.hs.gs.vo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hs.gs.domain.Department;
import com.hs.gs.domain.Patrol;
import com.hs.gs.domain.PatrolTime;
import com.hs.gs.exception.IllegalDataProcessException;

public class PatrolOfDepartmentVO {
	
	private Department department;
	private Date patrolDay;
	private List<PatrolOfClockAndDepartmentVO> patrols = new ArrayList<PatrolOfClockAndDepartmentVO>();
	
	public PatrolOfDepartmentVO(List<Patrol> patrols) throws IllegalDataProcessException {
		int startPoint = 0;
		Long lastClockId = null;
		if(patrols != null && patrols.size() > 0) {
			for(int i = 0; i < patrols.size(); i++) {
				Patrol patrol = patrols.get(i);
				if(department == null) {
					department = patrol.getDepartment();
				}
				if(patrolDay == null) {
					patrolDay = patrol.getPatrolDay();
				}
				if(lastClockId == null) {
					lastClockId = patrol.getPTime().getId();
				}
				if(!lastClockId.equals(patrol.getPTime().getId())) {
					PatrolOfClockAndDepartmentVO vo = 
						new PatrolOfClockAndDepartmentVO(patrols.subList(startPoint, i));
					this.patrols.add(vo);
					startPoint = i;
					lastClockId = patrol.getPTime().getId();
				}
			}
			if(startPoint < patrols.size()) {
				PatrolOfClockAndDepartmentVO vo = 
					new PatrolOfClockAndDepartmentVO(patrols.subList(startPoint, patrols.size()));
				this.patrols.add(vo);
			}
		}
	}

	public Department getDepartment() {
		return department;
	}

	public static List<PatrolOfDepartmentVO> populate(List<Patrol> patrols) {
		Long lastDepId = null;
		int startPosition = 0;
		List<PatrolOfDepartmentVO> vos = null;
		if(patrols != null) {
			vos = new ArrayList<PatrolOfDepartmentVO>();
			for(int i = 0; i < patrols.size(); i++) {
				Patrol p = patrols.get(i);
				Long currDepId = p.getId();
				if(lastDepId == null) {
					lastDepId = currDepId;
				}
				if(!lastDepId.equals(currDepId)) {
					try {
						PatrolOfDepartmentVO vo = 
							new PatrolOfDepartmentVO(patrols.subList(startPosition, i));
						vos.add(vo);
					} catch (IllegalDataProcessException e) {
						e.printStackTrace();
					}
					lastDepId = currDepId;
					startPosition = i;
				}
			}
			if(startPosition < patrols.size()) {
				try {
					PatrolOfDepartmentVO vo = new PatrolOfDepartmentVO(patrols.subList(startPosition, patrols.size()));
					vos.add(vo);
				} catch (IllegalDataProcessException e) {
					e.printStackTrace();
				}
			}
		}
		return vos;
	}
	
	public float getScore() {
		int totalCount = PatrolTime.findAllPatrolTimes().size();
		float totalScore = 0f;
		for(PatrolOfClockAndDepartmentVO vo : patrols) {
			totalScore += vo.getScore();
		}
		return totalScore/totalCount;
	}
	
	
}
